package com.tianheng.wanzhou.datacollecting.netty.kaiyuanzhengjing;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.ReferenceCountUtil;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


@Component(value = "kaiyuanzhenngjingClient")
public class MyClient {

    @Autowired
    private ObjectFactory<ClientHandler> factory;
    @Autowired
    IMachineListService machineListService;


    private List<MachineList> machineList = new ArrayList<>();

    //netty组件
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    Bootstrap bs = new Bootstrap();


    MyClient() {
        bs.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(factory.getObject());
                    }
                });
    }

    @PostConstruct
    private void postConstruct() {
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 0).eq("status", 1).eq("son_type", "03");
        machineList = machineListService.list(queryWrapper);
    }


    @Scheduled(cron = "0/10 * * * * ? ")
    public void sendMsg() {
        for (MachineList machine : this.machineList) {

            try{
                ChannelFuture cf = bs.connect(machine.getMacIp(), machine.getPort()).sync();
            }catch (Exception e){
                System.err.println(machine.getMacIp()+"连接失败" + e.getMessage());
            }



        }
    }

    //隔一小时更新一次设备列表
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void updateMacList() {
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 0).eq("status", 1).eq("son_type", "03");
        machineList = machineListService.list(queryWrapper);
    }
}
